﻿using AutoMapper;
using MediatR;
using RBAC.Domain.SmartHealthcare;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using SmartHealthcare.Write.Api.Application.Command.Department;

namespace SmartHealthcare.Write.Api.Application.Handler.Department
{
    public class CreateDepartmentHandler : IRequestHandler<CreateDepartmentCommand, APIResult<int>>
    {
        private readonly IBaseRepository<DepartmentModel> departRepository;
        private readonly IMapper mapper;
        private readonly ILogger<CreateDepartmentHandler> logger;

        public CreateDepartmentHandler(IBaseRepository<DepartmentModel> departRepository, IMapper mapper, ILogger<CreateDepartmentHandler> logger)
        {
            this.departRepository = departRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 创建科室
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(CreateDepartmentCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var model = mapper.Map<DepartmentModel>(request);
            var r = departRepository.Create(model);
            if (r > 0)
            { 
                res.Code = APIEnums.Success;
                res.Msg = "添加成功";
                res.Data = r;
                logger.LogInformation("添加部门成功");
                return Task.FromResult(res);
            }
            else
            {
                res.Code = APIEnums.Fail;
                res.Msg = "添加失败";
                res.Data = r;
                logger.LogError("添加部门失败");
                return Task.FromResult(res);
            }

        }
    }
}
